// 定义电机控制引脚
const int motorPin1 = 3;
const int motorPin2 = 5;
const int enablePin = 6;

void setup() {
  // 设置电机控制引脚为输出模式
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);
  // 初始化串口通信
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    char command = Serial.read();

    switch (command) {
      case 'F': // 正转
        digitalWrite(motorPin1, HIGH);
        digitalWrite(motorPin2, LOW);
        analogWrite(enablePin, 255); // 最大速度
        Serial.println("Motor is rotating forward.");
        break;
      case 'B': // 反转
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, HIGH);
        analogWrite(enablePin, 255); // 最大速度
        Serial.println("Motor is rotating backward.");
        break;
      case 'S': // 停止
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, LOW);
        analogWrite(enablePin, 0);
        Serial.println("Motor is stopped.");
        break;
      case 'V': // 变速
        if (Serial.available() > 0) {
          int speed = Serial.parseInt();
          if (speed >= 0 && speed <= 255) {
            analogWrite(enablePin, speed);
            Serial.print("Motor speed set to: ");
            Serial.println(speed);
          } else {
            Serial.println("Invalid speed value. Please enter a value between 0 and 255.");
          }
        }
        break;
    }
  }
}
